import { useTokenStore } from '@/stores/token'
import axios from 'axios'
import { ElMessage } from 'element-plus'

import router from '@/router'

const baseURL = '/api'
const instance = axios.create({
	baseURL,
	headers: {
		'Cache-Control': 'no-cache',
		Pragma: 'no-cache',
		Expires: '0',
	},
})

// 请求拦截器
instance.interceptors.request.use(
	(config) => {
		const tokenStore = useTokenStore()
		if (tokenStore.token) {
			config.headers.Authorization = tokenStore.token
		}
		// 添加时间戳参数以避免缓存
		if (config.method === 'get' || config.method === 'post') {
			config.params = {
				...config.params,
				cacheBuster: new Date().getTime(),
			}
		}
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 响应拦截器
instance.interceptors.response.use(
	(result) => {
		if (result.data.code === 0) {
			return result.data
		}
		ElMessage.error(result.data.message ? result.data.message : '服务异常')
		return Promise.reject(result.data)
	},
	(error) => {
		if (error.response.status === 401) {
			ElMessage.error('无权访问，请先登录')
			router.push('/login')
		} else {
			let message = '服务异常'
			if (error.response && error.response.data) {
				message = error.response.data.message || message
			}
			ElMessage.error(message)
			return Promise.reject(error)
		}
	}
)

export default instance
